<?php

/**
 * 授权登录,绑定,验证
 * @author : SongXing
 */
class OauthController extends UserBaseC {

    //布局
    public $layout = 'theme.views.layouts.FrontLogoHeaderContent';

    /**
     * Sina 微博授权登录
     * @author : SongXing
     */
    public function actionSina() {
        $curl = new Curl();
        $sUrl = "https://api.weibo.com/oauth2/access_token";
        $aGetParam = array(
            "code" => Yii::app()->request->getParam('code'), //用于调用access_token，接口获取授权后的access token
            "client_id" => Yii::app()->params->sinaAPI['WB_AKEY'], //申请应用时分配的AppSecret
            "client_secret" => Yii::app()->params->sinaAPI['WB_SKEY'], //申请应用时分配的AppSecret
            "grant_type" => "authorization_code", //请求的类型，可以为authorization_code、password、refresh_token。
            "redirect_uri" => Yii::app()->params->sinaAPI['WB_CALLBACK_URL'], //回调地址
        );
        $sContent = $curl->post($sUrl, $aGetParam);
        if (empty($sContent)) {
            $this->error("新浪微博授权失败！");
        }
        $aParam = json_decode($sContent, true);
        if (empty($aParam)) {
            $this->error("新浪微博授权失败！");
        }
        $session_array['token'] = $aParam['access_token'];
        $session_array['regdate'] = intval(time()) + intval($aParam['expires_in']);
        $session_array['openid'] = $aParam['uid'];
        $session_array['bind_type'] = 'sina';
        //检查是否已经绑定
        $bindInfo = MembersOauthModel::model()->isBind($session_array['bind_type'], $session_array);
        if ($bindInfo !== false) {
            if (Yii::app()->user->isLogged()) {
                $this->error('该帐号已经绑定其它帐号，无法进行绑定！', self::U('user/info/bund'));
            }
            //获取登录状态,直接登录
            Yii::app()->user->registerLogin(Yii::app()->user->getLocalUser((int) $bindInfo['uid']));
            $this->redirect(Yii::app()->user->returnUrl);
        } else {
            //如果是登录状态，直接绑定
            if (Yii::app()->user->isLogged()) {
                if (MembersOauthModel::model()->autoBind($session_array)) {
                    $this->success('帐号绑定成功！', self::U('user/info/bund'));
                    exit;
                } else {
                    $error = MembersOauthModel::model()->getOneError();
                    $this->error($error ? $error : '绑定帐号失败！');
                }
            }
            //把基本信息存入session
            Yii::app()->session->add('session_array', $session_array);
        }
        $this->redirect(array("/user/oauth/bind"));
    }

    /**
     * QQ 授权登录
     * Author : songxing
     */
    public function actionQQ() {
        $curl = new Curl();
        //QQAPI获取Token
        if ($_REQUEST['state'] == Yii::app()->session['state']) { //csrf
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                    . "client_id=" . Yii::app()->params->QQAPI['appid'] . "&redirect_uri=" . urlencode(Yii::app()->params->QQAPI['callback'])
                    . "&client_secret=" . Yii::app()->params->QQAPI['appkey'] . "&code=" . $_REQUEST["code"];
            $response = $curl->get($token_url);
            if (empty($response)) {
                $this->error('QQ授权失败！');
            }
            //解析返回参数
            $params = array();
            parse_str($response, $params);
            //set access token to session
            $session_array["token"] = $params["access_token"];
            $session_array['regdate'] = intval(time()) + intval($params["expires_in"]);
        } else {
            $this->error('QQ授权失败！');
        }
        unset(Yii::app()->session['state']);
        //QQAPI获取openid
        $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=" . $session_array['token'];
        $str = $curl->get($graph_url);
        preg_match('/callback\(\s+(.*?)\s+\)/i', $str, $aTemp);
        $user = json_decode($aTemp[1], true);
        //set openid to session
        $session_array['client_id'] = $user['client_id'];
        $session_array['openid'] = $user['openid'];
        $session_array['bind_type'] = 'qq';
        //取得授权用户基本信息
        $sUrl = "https://graph.qq.com/user/get_user_info?";
        $aGetParam = array(
            "access_token" => $session_array['token'],
            "oauth_consumer_key" => Yii::app()->params->QQAPI['appid'],
            "openid" => $user['openid'],
            "format" => "json"
        );
        $user_info = $curl->get($sUrl . http_build_query($aGetParam));
        //把json数据转换为数组
        $user_info = json_decode($user_info, true);
        $session_array['user_info'] = $user_info;
        //检查是否已经绑定
        $bindInfo = MembersOauthModel::model()->isBind($session_array['bind_type'], $session_array);
        if ($bindInfo !== false) {
            if (Yii::app()->user->isLogged()) {
                $this->error('该帐号已经绑定其它帐号，无法进行绑定！', self::U('user/info/bund'));
            }
            //获取登录状态,直接登录
            Yii::app()->user->registerLogin(Yii::app()->user->getLocalUser((int) $bindInfo['uid']));
            $this->redirect(Yii::app()->user->returnUrl);
        } else {
            //如果是登录状态，直接绑定
            if (Yii::app()->user->isLogged()) {
                if (MembersOauthModel::model()->autoBind($session_array)) {
                    $this->success('帐号绑定成功！', self::U('user/info/bund'));
                    exit;
                } else {
                    $error = MembersOauthModel::model()->getOneError();
                    $this->error($error ? $error : '绑定帐号失败！');
                }
            }
            //把基本信息存入session
            Yii::app()->session->add('session_array', $session_array);
            //没有绑定记录的直接注册
            //$uid = $this->RegAndBind();
            $this->redirect(array("/user/oauth/bind"));
        }
        $this->redirect(Yii::app()->user->returnUrl);
    }

    /**
     * 绑定账户方法
     * 需要设置Session
     * 	Yii::app()->session['session_array']['token'] 		= $token['access_token'];
     * 	Yii::app()->session['session_array']['regdate']		= time() + $token['expires_in '];
     * 	Yii::app()->session['session_array']['openid']		= $user_message['idstr'];
     * 	Yii::app()->session['session_array']['bind_type'] 	= 'sina';
     * Author : songxing
     */
    public function actionBind() {
        $model = new MembersModel();
        $MembersOauth = new MembersOauthModel();
        $session_array = Yii::app()->session['session_array'];
        if (empty($session_array)) {
            $this->error('授权信息错误，请重新授权登录！');
        }
        if (IS_POST) {
            //现有的账户进行绑定
            if ($_POST['submit_type'] == "login") {
                $post_array = $_POST['MembersModel']; //获取POST数据
                $userInfo = Yii::app()->user->getLocalUser($post_array['username'], $post_array['password']); //根据用户名,密码获取user数组
                $MemberOauthFind = new MembersOauthModel();
                //验证用户名密码通过
                if (!empty($userInfo)) {
                    //验证该UID 是否已经绑定
                    if ($MembersOauth->isUserBind($session_array['bind_type'], (int) $userInfo['uid'])) {
                        $this->error('该授权帐号已经绑定其他账户！');
                    }
                    //进行绑定
                    if ($MembersOauth->addBind($session_array['bind_type'], $session_array, $userInfo['uid'])) {
                        if (Yii::app()->user->login($post_array['username'], $post_array['password'])) {
                            Yii::app()->session->remove('session_array');
                            $this->redirect(Yii::app()->user->returnUrl);
                        } else {
                            $error = Yii::app()->user->getError();
                            $this->error($error ? $error : '登录失败！');
                        }
                    } else {
                        $error = $MembersOauth->getOneError();
                        $this->error($error ? $error : '绑定帐号失败！');
                    }
                } else {
                    $this->error("用户名或者密码错误，绑定失败！");
                }
            }
            // 新帐户注册
            if ($_POST['submit_type'] == "reg") {
                $post_array = $_POST['MembersModel'];
                $post_array['status'] = 1;
                UserRegister::getInstance()->data($post_array);
                $newUid = UserRegister::getInstance()->register();
                if ($newUid) {
                    if ($MembersOauth->addBind($session_array['bind_type'], $session_array, $newUid)) {
                        if (Yii::app()->user->login($post_array['username'], $post_array['password'])) {
                            Yii::app()->session->remove('session_array');
                            $this->redirect(Yii::app()->user->returnUrl);
                        } else {
                            $error = Yii::app()->user->getError();
                            $this->error($error ? $error : '登录失败！');
                        }
                    } else {
                        $error = $MembersOauth->getOneError();
                        $this->error($error ? $error : '绑定帐号失败！');
                    }
                } else {
                    $error = UserRegister::getInstance()->getError();
                    $this->error($error ? $error : '注册失败！');
                }
            }
        }
        $this->render('oauthlogin', array('model' => $model));
    }

    /**
     * 注册并且绑定账户(QQ用户第一次登录)
     * 用户名为openid
     * 密码随机
     * email为openid + "@qq.com"
     * 参数
     * Author : songxing
     */
//    public function RegAndBind() {
//
//        $model = array();
//        $array = Yii::app()->session['session_array'];
//        $model['type'] = 2;  //QQ注册的账户类型
//        $model['status'] = 1; //不发送邮件
//        $model['email'] = $array['openid'] . "@qq.com";
//        $model['username'] = $array['openid'];
//        $model['password'] = md5($array['openid'] . rand());
//        $model['repassword'] = $model['password'];
//        $model['regip'] = Yii::app()->request->userHostAddress;
//        $model['regdate'] = $_SERVER['REQUEST_TIME'];
//        $model['lastloginip'] = Yii::app()->request->userHostAddress;
//        $model['lastlogintime'] = $_SERVER['REQUEST_TIME'];
//
//        $MembersModel = new MembersModel();
//        $result = $MembersModel->find('username =  ?', array($model['username']));
//        if (!$result) {
//            $reg = new UserRegister();
//            $reg->data($model);
//            $result_uid = (int) $reg->register();
//        } else {
//            $result_uid = (int) $result->attributes['uid'];
//        }
//
//
//        //增加绑定记录(写入MembersOauth表)
//        $MembersOauth = new MembersOauthModel('create');
//        $MembersOauth->attributes = Yii::app()->session['session_array'];
//        $MembersOauth->uid = $result_uid;
//
//        if ($MembersOauth->validate()) {
//            $MembersOauth->save();
//        }
//
//
//        //获取登录状态,直接登录
//        $MembersModelstd = new MembersModel();
//        $MembersModel = Yii::app()->user->getLocalUser($result_uid);
//        //$userport = new UserPassport();
//        $result = Yii::app()->user->registerLogin($MembersModel);
//
//
//        return $result->attributes['uid'];
//    }

    /**
     * 新浪登录跳转到登录界面
     */
    public function actionSinaReg() {
        //请求参数
        $aParam = array(
            "client_id" => Yii::app()->params->sinaAPI['WB_AKEY'], //申请应用时分配的AppKey。
            "redirect_uri" => Yii::app()->params->sinaAPI['WB_CALLBACK_URL'], //授权回调地址
            "state" => '',
        );
        //对参数进行URL编码
        $aGet = array();
        foreach ($aParam as $key => $val) {
            $aGet[] = $key . "=" . urlencode($val);
        }
        //请求地址
        $sina_url = "https://api.weibo.com/oauth2/authorize?";
        $sina_url .= join("&", $aGet);
        header("location: " . $sina_url);
    }

    /**
     * QQ帐号登录跳转到登录页面
     */
    public function actionQQReg() {
        $state = md5(uniqid(rand(), TRUE)); //CSRF protection
        Yii::app()->session->add('state', $state);
        $qq_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id="
                . Yii::app()->params->QQAPI['appid'] . "&redirect_uri=" . urlencode(Yii::app()->params->QQAPI['callback'])
                . "&state=" . $state
                . "&scope=" . Yii::app()->params->QQAPI['scope'];
        header("location: " . $qq_url);
    }

}
